#!/bin/bash

# slackbuild script for libressl by D Woodfall
#
# WTFPL licence

# BUILD 2: Thanks to Naglfar:
#
#    --with-openssldir=/etc/$PRGNAM \
#
# NOTE: PKG_CONFIG_PATH will likely need setting in your build scripts:
#
# PKG_CONFIG_PATH=/usr/lib$LIBDIRSUFFIX/libressl/pkgconfig:$PKG_CONFIG_PATH \
# ./configure \
#   ...

cd $(dirname $0) ; CWD=$(pwd)

PRGNAM=libressl
VERSION=${VERSION:-3.7.1}
BUILD=${BUILD:-1}
TAG=${TAG:-_SBo}
PKGTYPE=${PKGTYPE:-tgz}

if [ -z "$ARCH" ]; then
  case "$( uname -m )" in
    i?86) ARCH=i586 ;;
    arm*) ARCH=arm ;;
       *) ARCH=$( uname -m ) ;;
  esac
fi

if [ ! -z "${PRINT_PACKAGE_NAME}" ]; then
  echo "$PRGNAM-$VERSION-$ARCH-$BUILD$TAG.$PKGTYPE"
  exit 0
fi

TMP=${TMP:-/tmp/SBo}
PKG=$TMP/package-$PRGNAM
OUTPUT=${OUTPUT:-/tmp}

if [ "$ARCH" = "i586" ]; then
  SLKCFLAGS="-O2 -march=i586 -mtune=i686"
  LIBDIRSUFFIX=""
elif [ "$ARCH" = "i686" ]; then
  SLKCFLAGS="-O2 -march=i686 -mtune=i686"
  LIBDIRSUFFIX=""
elif [ "$ARCH" = "x86_64" ]; then
  SLKCFLAGS="-O2 -fPIC"
  LIBDIRSUFFIX="64"
else
  SLKCFLAGS="-O2"
  LIBDIRSUFFIX=""
fi

set -e

rm -rf $PKG
mkdir -p $TMP $PKG $OUTPUT
cd $TMP
rm -rf $PRGNAM-$VERSION
tar xvf $CWD/$PRGNAM-$VERSION.tar.gz
cd $PRGNAM-$VERSION
chown -R root:root .
find . -perm /111 -a \! -perm 755 -a -exec chmod 755 {} + \
 -o \! -perm /111 -a \! -perm 644 -a -exec chmod 644 {} +

# Don't install man page symlinks
sed -i '/ln -sf.*\.3"$/d' man/Makefile.in

if [ "${MANPAGES:-no}" = no ]; then
  sed -i '/man\/Makefile/d' configure.ac
  autoreconf -f
  sed -i "s, man , ,g; s, install-man , ,g" Makefile.in
fi

CFLAGS="$SLKCFLAGS" \
CXXFLAGS="$SLKCFLAGS" \
./configure \
  --enable-nc \
  --disable-tests \
  --disable-static \
  --prefix=/usr \
  --libdir=/usr/lib${LIBDIRSUFFIX}/$PRGNAM \
  --includedir=/usr/include/$PRGNAM \
  --with-openssldir=/etc/$PRGNAM \
  --program-prefix "$PRGNAM-" \
  --mandir=/usr/man \
  --docdir=/usr/doc/$PRGNAM-$VERSION \
  --build=$ARCH-slackware-linux

make
make install DESTDIR=$PKG

rm -f $PKG/usr/lib${LIBDIRSUFFIX}/$PRGNAM/*.la

find $PKG/usr/man -type f -exec gzip -9 {} \;

mkdir -p $PKG/etc/ld.so.conf.d/
echo /usr/lib${LIBDIRSUFFIX}/$PRGNAM > $PKG/etc/ld.so.conf.d/$PRGNAM.conf

find $PKG -print0 | xargs -0 file | grep -e "executable" -e "shared object" | grep ELF \
  | cut -f 1 -d : | xargs strip --strip-unneeded 2> /dev/null || true

mkdir -p $PKG/usr/doc/$PRGNAM-$VERSION
cp -a \
  COPYING ChangeLog README.md \
  $PKG/usr/doc/$PRGNAM-$VERSION
cat $CWD/README > $PKG/usr/doc/$PRGNAM-$VERSION/README
cat $CWD/$PRGNAM.SlackBuild > $PKG/usr/doc/$PRGNAM-$VERSION/$PRGNAM.SlackBuild
cat $CWD/$PRGNAM-$VERSION-relnotes.txt > \
  $PKG/usr/doc/$PRGNAM-$VERSION/$PRGNAM-$VERSION-relnotes.txt

mkdir -p $PKG/install
cat $CWD/slack-desc > $PKG/install/slack-desc
cat $CWD/doinst.sh > $PKG/install/doinst.sh
cat $CWD/douninst.sh > $PKG/install/douninst.sh

cd $PKG
/sbin/makepkg -l y -c n $OUTPUT/$PRGNAM-$VERSION-$ARCH-$BUILD$TAG.$PKGTYPE
